package com.xiaoye.digitaltwin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xiaoye.digitaltwin.common.R;
import com.xiaoye.digitaltwin.entity.Neiya;
import com.xiaoye.digitaltwin.entity.Student;
import com.xiaoye.digitaltwin.service.NeiyaService;
import com.xiaoye.digitaltwin.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Random;

/**
 *内压实验表
 * Create by xiaoye on 2023/3/31
 */
@Slf4j
@RestController
@RequestMapping("/neiya")
public class NeiyaController {

    @Autowired
    private NeiyaService neiyaService;

    @Autowired
    private StudentService studentService;

    @Value("${digital.path.neiya.report}")
    private String uploadReports;

    @Value("${digital.path.neiya.data}")
    private String downloadData;


    /**
     *根据传递过来的压力值，计算出相应的图片名称，并将图片名称存储起来
     * @param request
     * @param stress
     */
    @PostMapping("/stress")
    public void handleStress(HttpServletRequest request,double stress){
//        if(stress)
        String xStress = "x_stress_" + stress + ".jpeg";
        String zStress = "z_stress_" + stress + ".jpeg";


        //获取学生id
        String stuId = null;
        try {
            stuId = request.getSession().getAttribute("studentId").toString();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        //获取学生学号
        Student stu = studentService.getById(stuId);
        String stuNo = stu.getStuNo();

        //从内压表进行查询操作
        LambdaQueryWrapper<Neiya> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Neiya::getStuNo,stuNo);
        Neiya neiyaStu = neiyaService.getOne(queryWrapper);

        //如果内压表中没有该学生信息，进行新增操作
        if(neiyaStu == null){
            //为非空字段设置值
            Neiya neiya = new Neiya();
            neiya.setStuNo(stuNo);
            neiya.setStress(stress);
            neiya.setXStressPath(xStress);
            neiya.setZStressPath(zStress);
            neiyaService.save(neiya);
            return;
        }else {
        //如果内压表中已经有该学生信息，进行更新操作
            LambdaUpdateWrapper<Neiya> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Neiya::getStuNo,stuNo);
            updateWrapper.set(Neiya::getStress,stress);
            updateWrapper.set(Neiya::getXStressPath,xStress);
            updateWrapper.set(Neiya::getZStressPath,zStress);
            neiyaService.update(updateWrapper);
        }
    }

    /**
     * 返回该学生对应的X方向应力云图名称
     * @param request
     * @return
     */
    @GetMapping("/xpicture")
    public R<String> returnX(HttpServletRequest request){

        //获取学生id
        String stuId = null;
        try {
            stuId = request.getSession().getAttribute("studentId").toString();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("未登录，session为空");
        }

        //查询学生学号
        Student stu = studentService.getById(stuId);
        String stuNo = stu.getStuNo();

        //从内压表查询该学生对应记录
        LambdaQueryWrapper<Neiya> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Neiya::getStuNo,stuNo);
        Neiya neiyaStu = neiyaService.getOne(queryWrapper);

        //出现异常导致内压表中没有数据
        if(neiyaStu == null)
            return R.error("数据库暂无数据");

        String xPicture = neiyaStu.getXStressPath();
        return R.success(xPicture);
    }

    /**
     * 返回该学生对应的Z方向应力云图名称
     * @param request
     * @return
     */
    @GetMapping("/zpicture")
    public R<String> returnZ(HttpServletRequest request){
        //获取学生id
        String stuId = null;
        try {
            stuId = request.getSession().getAttribute("studentId").toString();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("未登录，session为空");
        }

        //查询学生学号
        Student stu = studentService.getById(stuId);
        String stuNo = stu.getStuNo();

        //从内压表该学生对应记录
        LambdaQueryWrapper<Neiya> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Neiya::getStuNo,stuNo);
        Neiya neiyaStu = neiyaService.getOne(queryWrapper);

        //出现异常导致内压表中没有数据
        if(neiyaStu == null)
            return R.error("数据库暂无数据");

        String zPicture = neiyaStu.getZStressPath();
        return R.success(zPicture);
    }


    /**
     * 学生上传实验报告
     * @param request
     * @param file
     * @return
     */
    @PostMapping("/report")
    public R<String> uploadReport(HttpServletRequest request, MultipartFile file){
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //获取学生id
        String stuId = null;
        try {
            stuId = request.getSession().getAttribute("studentId").toString();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("未登录，session为空");
        }
        //查询学生学号
        Student stu = studentService.getById(stuId);
        String stuNo = stu.getStuNo();

        String reportname = stuNo + suffix;

        //将上传的文件保存在指定路径
        File dir = new File(uploadReports);
        if(!dir.exists()){
            //目录不存在，需要创建
            dir.mkdirs();
        }
        try {
            //将临时文件转存到指定位置
            file.transferTo(new File(uploadReports + reportname));
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("报告上传失败");
        }

        //将报告名称保存入内压表
        LambdaUpdateWrapper<Neiya> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Neiya::getStuNo,stuNo);
        updateWrapper.set(Neiya::getReport,reportname);
        neiyaService.update(updateWrapper);
        return R.success(reportname);
    }

    /**
     * 学生下载随机实验报告
     * @param request
     */
    @GetMapping("/data")
    public void downloadData(HttpServletRequest request, HttpServletResponse response){
        //获取学生id
        String stuId = null;
        try {
            stuId = request.getSession().getAttribute("studentId").toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //查询学生学号
        Student stu = studentService.getById(stuId);
        String stuNo = stu.getStuNo();

        //查询一下该学生在内压实验表中的download字段是否有值
        LambdaQueryWrapper<Neiya> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Neiya::getStuNo,stuNo);
        Neiya neiyaStu = neiyaService.getOne(queryWrapper);
        String download = neiyaStu.getDownload();

        if(download == null){
            //没有值，产生随机的实验报告

            //随机浮点数生成并保留一位小数
            float aFloat = new Random().nextFloat() * 0.9f + 0.1f;
            DecimalFormat decimalFormat = new DecimalFormat("#.#");
            String format = decimalFormat.format(aFloat);
            String reportName = format + "Mpa.zip";

            try {
                //输入流，通过输入流读取文件内容
                FileInputStream fileInputStream = new FileInputStream(new File(downloadData + reportName));

                //输出流，通过输出流将文件写回浏览器
                ServletOutputStream outputStream = response.getOutputStream();
                response.setContentType("application/octet-stream");
                //这里设置返回文件的名称，没设置的话，返回文件名称为response.bin
                response.setHeader("Content-Disposition", "attachment; filename=" + reportName);

                int len = 0;
                byte[] bytes = new byte[1024];
                while ((len = fileInputStream.read(bytes)) != -1){
                    outputStream.write(bytes,0,len);
                    outputStream.flush();
                }

                //关闭资源
                outputStream.close();
                fileInputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            //将报告名存入内压表
            LambdaUpdateWrapper<Neiya> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Neiya::getStuNo,stuNo);
            updateWrapper.set(Neiya::getDownload,reportName);
            neiyaService.update(updateWrapper);

        }else {
            //有值，返回对应的实验报告
            try {
                //输入流，通过输入流读取文件内容
                FileInputStream fileInputStream = new FileInputStream(new File(downloadData + download));

                //输出流，通过输出流将文件写回浏览器
                ServletOutputStream outputStream = response.getOutputStream();
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment; filename=" + download);

                int len = 0;
                byte[] bytes = new byte[1024];
                while ((len = fileInputStream.read(bytes)) != -1){
                    outputStream.write(bytes,0,len);
                    outputStream.flush();
                }
                //关闭资源
                outputStream.close();
                fileInputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 学生反馈信息
     * @param request
     * @return
     */
    @PutMapping("/feedback")
    public R<String> feedback(HttpServletRequest request,String msg){
        //获取学生id
        String stuId = null;
        try {
            stuId = request.getSession().getAttribute("studentId").toString();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("学生未登录");
        }

        //查询学生学号
        Student stu = studentService.getById(stuId);
        String stuNo = stu.getStuNo();

        LambdaUpdateWrapper<Neiya> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Neiya::getStuNo,stuNo);
        updateWrapper.set(Neiya::getFeedback,msg);
        neiyaService.update(updateWrapper);
        return  R.success("提交反馈成功");
    }
}
